#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QDebug>
#include <QFileDialog>
#include <QDateTime>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //设置菜单栏
    this->setWindowTitle("My Text");
    QMenu* menu = ui->menubar->addMenu("File");
    QAction *openAction = menu->addAction("Open");
    QAction *saveAction = menu->addAction("Save");

    //处理打开文件
    connect(openAction, &QAction::triggered, this, [=](){
       const QString& filename = QFileDialog::getOpenFileName();

       //在状态栏显示文件路径
       ui->statusbar->showMessage(filename);

       QFile file(filename);
       //只读方式打开
       file.open(QIODevice::ReadOnly);
       if(!file.isOpen())
       {
           qDebug() << "Open failed";
           file.close();
       }

       const QString& contents = file.readAll();
       ui->textEdit->setText(contents);

       file.close();
    });

    //处理保存文件
    connect(saveAction, &QAction::triggered, this, [=](){
        const QString& filename = QFileDialog::getSaveFileName();

        //在状态栏显示文件路径
        ui->statusbar->showMessage(filename);

        QFile file(filename);
        //只读方式打开
        file.open(QIODevice::WriteOnly);
        if(!file.isOpen())
        {
            qDebug() << "Open failed";
            file.close();
        }

        const QString& contents = ui->textEdit->toPlainText();
        file.write(contents.toUtf8());

        file.close();
    });
}


MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    QFileInfo fileinfo(QFileDialog::getOpenFileName());
    QString msgInfo;
    //⽂件名
    qDebug() << "⽂件名为：" << fileinfo.fileName().toUtf8().data();
    msgInfo += QString("⽂件名为：") + fileinfo.fileName().toUtf8().data() + QString("\n");

    //⽂件后缀名
    qDebug() << "后缀名为：" << fileinfo.suffix().toUtf8().data();
    msgInfo += QString("后缀名为：") + fileinfo.suffix().toUtf8().data() + QString("\n");

    //⽂件⼤⼩
    msgInfo += QString("⽂件⼤⼩为：") + QString::number(fileinfo.size()) + QString("\n");

    //⽂件路径
    msgInfo += QString("⽂件路径为：") + fileinfo.path().toUtf8().data() + QString("\n");

    //判断是否为⽂件
    msgInfo += QString("是否为⽂件：") + fileinfo.isFile() + QString("\n");

    //⽂件创建时间
    QDateTime time1 = fileinfo.fileTime(QFileDevice::FileBirthTime);
    msgInfo += QString("创建时间为：") + time1.toString("yyyy-MM-ddhh:mm:ss").toUtf8().data() + QString("\n");

    QMessageBox::information(this, "message", msgInfo);
}
